package reflect;

import reflect.com.webserver.core.URIDemo;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URISyntaxException;

/**
 * @author DBX
 * @effect 访问一个文件所有的main方法
 * 首先获取文件的类路径，找到目标文件的类路径
 * 获取文件下的类，遍历通过反射创建实例对象，调用main方法
 * @date 2021/09/15/19:20
 */
public class ReflectDemo10 {
    public static void main(String[] args) throws ClassNotFoundException, URISyntaxException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
//        Class c = Class.forName("reflect.com.webserver.core.URIDemo");
//        String path = c.getClassLoader().getResource(".").toURI().toString();
        File file = new File(URIDemo.class.getClassLoader().getResource(".").toURI());
        String path =file.getAbsolutePath() ;
        System.out.println(path);
        File file1 = new File(path+"\\day09API\\file");
        System.out.println(file1.getAbsolutePath());

       File[] subs =  file1.listFiles(f->f.getName().endsWith(".class")&&!f.getName().contains("$"));
        for (File sub : subs) {
            String fileName = sub.getName();
            String className = fileName.substring(0,fileName.indexOf("."));
            Class cls = Class.forName("day09API.file."+className);
//            Object obj = cls.newInstance();
//            System.out.println(obj);

//            执行静态方法main
            Method method = cls.getMethod("main",String[].class);
            System.out.println("开始执行"+className+"的main方法");
            method.invoke(null,(Object)new String[0]);
        }

    }
}
